import type { ProColumns } from '@ant-design/pro-components';
import { DrawerForm, EditableProTable, ProForm, ProFormSelect } from '@ant-design/pro-components';
import { Button, Form } from 'antd';
import { useMemo, useState } from 'react';
import api from './request';

export type FormConfig = { Component: any; props: Record<string, any> };
export interface Props {
  type: 'warehouse' | 'shipment';
  data?: InventoryManagementApi.ListResponse;
  onSuccess?: () => void;
  onCancel?: () => void;
}
function ShopListBindForm(props: Props) {
  const { type } = props;

  const [form] = Form.useForm();
  const [formData, setFormData] = useState<any>({});
  const [allList, setAllList] = useState<InventoryManagementApi.ListResponse[]>([]);

  const allListOptions = useMemo(
    () => allList.map((item) => ({ label: item.goodsname, value: item.goodsid })),
    [allList],
  );

  const getAllList = async () => {
    const data = await api.getAllList();
    setAllList(data);
  };

  const onOpenChange = (open: boolean) => {
    if (open) {
      getAllList();
    } else {
      form.resetFields();
      setFormData({});
      props.onCancel?.();
    }
  };
  const onSubmit = async () => {
    const data: any = {};
    if (data.success) props.onSuccess?.();
    return data.success;
  };

  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>(() => [].map((item) => item));

  const columns: ProColumns<GoodsListManagementApi.SkuInfo>[] = [
    {
      title: '规格名称',
      dataIndex: 'skuName',
    },
    {
      title: '库存数量',
      dataIndex: 'inventoryQty',
      valueType: 'digit',
    },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.id);
          }}
        >
          编辑
        </a>,
        <a key="delete" onClick={() => {}}>
          删除
        </a>,
      ],
    },
  ];

  return (
    <DrawerForm
      autoFocusFirstInput
      title={type === 'warehouse' ? '入仓' : '出仓'}
      form={form}
      drawerProps={{ destroyOnClose: true }}
      resize={{
        maxWidth: window.innerWidth * 0.8,
        minWidth: 720,
        onResize() {},
      }}
      trigger={
        type === 'warehouse' ? <Button type="link">入仓</Button> : <Button type="link">出仓</Button>
      }
      onOpenChange={onOpenChange}
      onFinish={onSubmit}
    >
      <Button type="primary">选择商品</Button>
      <ProFormSelect
        required
        name="shopId"
        label="仓库列表"
        placeholder="请选择仓库"
        options={allListOptions}
        fieldProps={{
          mode: 'multiple',
          value: formData.shopId,
          onChange: (value, options) => {
            // @ts-ignore
            const getMerchantShopDataOutputs = options.map((option: any) => ({
              shopId: option.value,
              shopName: option.label,
            }));
            setFormData({ ...formData, shopId: value, getMerchantShopDataOutputs });
          },
        }}
      />
      <ProForm.Item rules={[{ required: true }]} name="skuInput" trigger="onValuesChange">
        <EditableProTable<GoodsListManagementApi.SkuInfo>
          controlled
          rowKey="id"
          toolBarRender={false}
          recordCreatorProps={false}
          columns={columns}
          editable={{
            type: 'multiple',
            editableKeys,
            onChange: setEditableRowKeys,
            actionRender: (row, _, dom) => {
              return [dom.save, dom.delete];
            },
          }}
          value={formData.skuInput}
          onChange={() => {}}
        />
      </ProForm.Item>
    </DrawerForm>
  );
}

export default ShopListBindForm;
